<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.gxgyl.com All rights reserved.

// +----------------------------------------------------------------------
// | Author: Liuyu
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\model\shiyao;

use app\api\model\shiyao\PayImage as PayImageModel;
use app\api\model\shiyao\PayOpenImage as PayImageOpenModel;
use app\api\model\User as UserModel;
use app\api\service\User as UserService;
use app\common\model\shiyao\ProjectPay as ProjectPayModel;
use cores\exception\BaseException;
use think\facade\Db;

/**
 * 模型
 * Class
 * @package app\common\model
 */
class ProjectPay extends ProjectPayModel {
	/**
	 * 隐藏字段
	 * @var array
	 */
	protected $hidden = [
		'is_delete',
		'store_id',

		'update_time',
	];

	public function getListExport(array $params = []) {
		$user = UserService::getCurrentLoginUser();
		// 查询参数
		$params = $this->setQueryDefaultValue($params, ['projectId' => -1, 'search' => '',
			'create_time_start' => '', 'pay_time_start' => '', 'center_id' => -1]);
		$filter = [];
		$params['center_id'] > 0 && $filter[] = ['pay.center_id', '=', $params['center_id']];
		if ($user['company_id'] > 0) {

			$filter[] = ['p.company_id', '=', $user['company_id']];
			//$filter[] = ['p.pm_id', '=', $user['user_id']];
		} else {
			$filter[] = ['p.company_id', '=', -1];
		}
		$filter[] = ['p.status', '=', 1];
		$params['projectId'] > 0 && $filter[] = ['p.project_id', '=', $params['projectId']];

		!empty($params['search']) && $filter[] = ['t.name|t.code', 'like', "%{$params['search']}%"];

		if (!empty($params['create_time_start'])) {
			$filter[] = ['pay.create_time', '>=', strtotime($params['create_time_start'])];
			$filter[] = ['pay.create_time', '<', strtotime($params['create_time_end']) + 86400];
		}
		if (!empty($params['pay_time_start'])) {
			$filter[] = ['pay.pay_time', '>=', strtotime($params['pay_time_start'])];
			$filter[] = ['pay.pay_time', '<', strtotime($params['pay_time_end']) + 86400];
		}

		// 实例化新查询对象
		$query = $this->getNewQuery();

		return $query->alias('pay')->with(['testee', 'project', 'user', 'refer', 'category', 'center'])
			->join('shiyao_project_center_testee t', 't.testee_id=pay.testee_id')
			->join('shiyao_project p', 'p.project_id=pay.project_id')
			->field('pay.*,t.name,t.name_suoxie')
			->where($filter)
			->where('pay.is_delete', '=', 0)
			->order('pay.create_time desc')
			->select()->toArray();
	}

	public function getListPi(array $params = []) {
		$userId = UserService::getCurrentLoginUserId();
		$filter = [];
		$filter[] = ['pay.center_id', '=', $params['centerId']];
		//$filter[] = ['pay.status', '<', 20];
		//$filter[] = ['pay.pm_status', '=', 0];

		if ($params['status'] == 0) {
			//待审批
			$filter[] = ['pay.pi_status', '=', 0];

		}
		if ($params['status'] == 1) {
			//审批通过
			$filter[] = ['pay.pi_status|pay.pm_status', '=', 1];

		}
		if ($params['status'] == 2) {
			//审批拒绝
			$filter[] = ['pay.pi_status|pay.pm_status', '=', 2];

		}

		!empty($params['search']) && $filter[] = ['t.name|t.code', 'like', "%{$params['search']}%"];

		// 实例化新查询对象
		$query = $this->getNewQuery();

		return $query->alias('pay')->with(['testee', 'project', 'user', 'refer', 'category'])
			->join('shiyao_project_center_testee t', 't.testee_id=pay.testee_id')
			->field('pay.*,t.name,t.name_suoxie')
			->where($filter)
			->where('pay.is_delete', '=', 0)
			->order('pay.create_time desc')
			->select()->toArray();
	}

	public function getListPm(array $params = []) {
		// 实例化新查询对象
		$query = $this->getNewQuery();
		$user = UserService::getCurrentLoginUser();
		$userId = $user['user_id'];
		$filter = [];
		$filter[] = ['pay.center_id', '=', $params['centerId']];
		$filter[] = ['pay.status', '<', 30];

		$filter[] = ['p.level', '=', 2];

		if ($params['status'] == 0) {
			//待审批
			$filter[] = ['pay.status', '=', 10];

		}
		if ($params['status'] == 1) {
			//审批通过
			$filter[] = ['pay.status', '=', 11];

		}
		if ($params['status'] == 2) {
			//审批拒绝
			$filter[] = ['pay.status', '=', 12];

		}
		if ($params['status'] == 3) {
			//已付款
			$filter[] = ['pay.status', '=', 21];

		}

		!empty($params['search']) && $filter[] = ['t.name|t.code', 'like', "%{$params['search']}%"];

		$store_user = Db::name('store_user')->where('user_name', $user['mobile'])->find();

		//根据角色筛选
		$role = Db::name('store_user_role')->where('role_id', 'in', [10006, 10009])
			->where('store_user_id', $store_user['store_user_id'])->find();

		if ($role) {
		} else {
			//审批人员
			$centerIds = Db::name('shiyao_project_center_pm')
				->where('pm_id', $userId)
				->where('center_id', $params['centerId'])
				->group('center_id')->select()->toArray();
			$centerIds = array_column($centerIds, 'center_id');

			//自己添加的项目
			$pmcenter = Db::name('shiyao_project_center')
			->where('id', $params['centerId'])
			->where('pm_id', $userId)->field('id')->select()->toArray();
			$centerIds2 = array_column($pmcenter, 'id');
			$newcenterIds = array_merge($centerIds, $centerIds2);

			if ($newcenterIds) {

				//print_r($newcenterIds);
				$query->where('pay.center_id', 'in', $newcenterIds);
			} else {
				$query->where('pay.center_id', -1);
			}

		}

		$lists = $query->alias('pay')->with(['testee', 'project', 'user', 'refer', 'category', 'center', 'auditPi', 'auditPm'])
			->join('shiyao_project_center_testee t', 't.testee_id=pay.testee_id')
			->join('shiyao_project p', 'p.project_id=pay.project_id')
			->field('pay.*,t.name,t.name_suoxie')
			->where($filter)
			->where('pay.is_delete', '=', 0)
			->order('pay.create_time desc')
			->select()->toArray();

		foreach ($lists as &$item) {
			if ($role) {
				$item['is_can'] = 1;
			} else {
				//是否具有审批权限
				$item['is_can'] = in_array($item['center_id'], $centerIds) ? 1 : 0;
			}

		}

		return $lists;
	}

	/**
	 *
	 * @return \think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws BaseException
	 */
	public function getList(array $params = []) {
		$userId = UserService::getCurrentLoginUserId();
		$filter = [];
		$filter[] = ['pay.center_id', '=', $params['centerId']];
		$params['status'] > -1 && $filter[] = ['pay.status', '=', $params['status']];

		if ($params['status'] == 11) {
			$filter[] = ['pay.pay_status', '=', 0];

		}

		!empty($params['search']) && $filter[] = ['t.name|t.code', 'like', "%{$params['search']}%"];

		// 实例化新查询对象
		$query = $this->getNewQuery();

		return $query->alias('pay')->with(['testee', 'project', 'user', 'refer', 'category', 'auditPm', 'auditPi'])
			->join('shiyao_project_center_testee t', 't.testee_id=pay.testee_id')
			->field('pay.*,t.name,t.name_suoxie')
			->where($filter)
			->where('pay.is_delete', '=', 0)
			->order('pay.create_time desc')
			->select()->toArray();
	}

	public function getListUser(array $params = []) {
		$userId = UserService::getCurrentLoginUserId();
		$filter = [];

		$params['status'] > -1 && $filter[] = ['pay.status', '=', $params['status']];

		if (isset($params['testeeId'])) {
			$filter[] = ['pay.testee_id', '=', $params['testeeId']];
			!empty($params['search']) && $filter[] = ['t.mobile|t.code', '=', trim($params['search'])];
		} else {
			if (trim($params['search']) == '') {
				$filter[] = ['t.mobile', '=', 1];
			} else {
				$filter[] = ['t.mobile|t.code', '=', trim($params['search'])];
			}
		}

		// 实例化新查询对象
		$query = $this->getNewQuery();

		return $query->alias('pay')->with(['testee', 'project', 'user', 'category', 'refer'])
			->join('shiyao_project_center_testee t', 't.testee_id=pay.testee_id')
			->field('pay.*,t.name,t.name_suoxie')
			->where($filter)
			->where('pay.is_delete', '=', 0)
			->order('pay.create_time desc')
			->select()->toArray();
	}

	/**
	 * 新增
	 * @param array $data
	 * @return mixed
	 * @throws BaseException
	 */
	public function add(array $data) {
		// 当前用户信息
		$user = UserService::getCurrentLoginUser(true);

		// 添加
		return $this->transaction(function () use ($user, $data) {

			//$data['out_time'] = strtotime($data['date']);
			$data['create_time'] = time();
			$testee = Db::name('shiyao_project_center_testee')->where('testee_id', $data['testee_id'])->find();

			$level = Db::name('shiyao_project')->where('project_id', $data['project_id'])->value('level');

			$data = array_merge($data, [
				'bank_file_id' => $testee['bank_file_id'],
				'bank_real_name' => $testee['bank_real_name'],
				'bank_name' => $testee['bank_name'],
				'bank_num' => $testee['bank_num'],
				'alipay' => $testee['alipay'],
				'level' => $level,
				'refer_id' => $user['user_id'],
				'store_id' => self::$storeId,
			]);
			$this->save($data);

			// 新增付款与图片关联-原始凭证
			PayImageModel::increased((int) $this['id'], $data['uploade2']);

			// 新增付款与图片关联-脱敏凭证
			PayImageOpenModel::increased((int) $this['id'], $data['uploade']);

			return true;
		});
	}

	/**
	 * 支付申请
	 * @param array $data
	 * @return mixed
	 * @throws BaseException
	 */
	public function payApply(array $data) {
		// 当前用户信息
		$user = UserService::getCurrentLoginUser(true);

		// 添加
		return $this->transaction(function () use ($user, $data) {

			$ids = $data['ids'];

			foreach ($ids as $key => $id) {

				$logData['fee_type'] = $data['fee_type'];
				$logData['total_money'] = $data['total_money'];
				$logData['payee_type'] = $data['payee_type'];
				$logData['payee'] = $data['payee'];
				$logData['payee_id'] = $data['payee_id'];
				$logData['payee_role'] = $data['payee_role'];
				$logData['pay_status'] = 1; //待支付
				$logData['pay_status_time'] = time();
				$logData['status'] = 20; //待支付

				Db::name('shiyao_project_pay_log')->where('id', $id)->update($logData);
			}

			return true;
		});
	}

	/**
	 * 审核
	 * @param array $data
	 * @return bool
	 * @throws BaseException
	 */
	public function editPi(array $data) {

		// 当前用户信息
		$user = UserService::getCurrentLoginUser(true);

		// 添加
		return $this->transaction(function () use ($user, $data) {

			$data['audit_time_pi'] = time();
			$data['audit_pi_id'] = $user['user_id'];
			if ($data['pi_status'] == 1 && $data['level'] == 1) {
				$data['status'] = 11;

			}
			if ($data['pi_status'] == 1 && $data['level'] == 2) {
				$data['status'] = 10;
			}
			if ($data['pi_status'] == 2) {
				$data['status'] = 12;
			}
			unset($data['level']);

			$this->save($data);

			return true;
		});

	}

	/**
	 * 审核
	 * @param array $data
	 * @return bool
	 * @throws BaseException
	 */
	public function editPm(array $data) {

		// 当前用户信息
		$user = UserService::getCurrentLoginUser(true);

		// 添加
		return $this->transaction(function () use ($user, $data) {

			$data['audit_time_pm'] = time();
			if ($data['pm_status'] == 1) {
				$data['status'] = 11;
			}
			if ($data['pm_status'] == 2) {
				$data['status'] = 12;
			}
			$data['audit_pm_id'] = $user['user_id'];

			$this->save($data);

			return true;
		});

	}

	/**
	 * 编辑收货地址
	 * @param array $data
	 * @return bool
	 * @throws BaseException
	 */
	public function edit(array $data) {

		// 当前用户信息
		$user = UserService::getCurrentLoginUser(true);

		// 添加
		return $this->transaction(function () use ($user, $data) {

			$data['out_time'] = strtotime($data['date']);

			$data = array_merge($data, [
				'refer_id' => $user['user_id'],
				'store_id' => self::$storeId,
			]);
			unset($data['create_time']);
			$this->save($data);

			// 新增付款与图片关联-原始凭证
			PayImageModel::updates((int) $this['id'], $data['uploade2']);

			// 新增付款与图片关联-脱敏凭证
			PayImageOpenModel::updates((int) $this['id'], $data['uploade']);

			return true;
		});

	}

	/**
	 * 删除
	 * @return bool
	 * @throws BaseException
	 */
	public function remove() {
		// 查询当前是否为默认地址
		$user = UserService::getCurrentLoginUser(true);
		// 清空默认地址
		if ($user['address_id'] == $this['address_id']) {
			UserModel::updateBase(['address_id' => 0], ['user_id' => $this['user_id']]);
		}
		// 标记为已删除
		return $this->save(['is_delete' => 1]);
	}

	/**
	 * 收货地址详情
	 * @param int $addressId
	 * @return UserAddress|array|null
	 * @throws BaseException
	 */
	public static function detail(int $logId) {

		$user = UserService::getCurrentLoginUser();
		$userId = $user['user_id'];
		$role = json_decode($user['role'], true);
		$role = $role ? $role : [];

		$detail = self::get(['id' => $logId], ['images.file', 'openImages.file', 'testee', 'refer', 'category', 'center']);
		if (empty($detail)) {
			throwError('未找到该项目');
		}
		$detail['can_do'] = 0;

		$store_user = Db::name('store_user')->where('user_name', $user['mobile'])->find();
		if ($store_user) {
			//根据角色筛选
			$role = Db::name('store_user_role')->where('role_id', 'in', [10006, 10009])
				->where('store_user_id', $store_user['store_user_id'])->find();

			if ($role) {
				$detail['can_do'] = 1;
			} else {
				$pmids = Db::name('shiyao_project_center_pm')->where('center_id', $detail['center_id'])->select()->toArray();
				$pmids = array_column($pmids, 'pm_id');
				$pmids = $pmids ? $pmids : [];
				if (in_array($userId, $pmids)) {
					//审批人员
					$detail['can_do'] = 1;
				}
			}
		}

		return $detail;
	}
}
